import { Button } from 'antd';
import * as Excel from 'exceljs';
import { saveAs } from 'file-saver';
import { useState } from 'react';

const ExportTradeReport = () => {
  const [loading, setLoading] = useState(false);

  const handleExport = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        'http://localhost:8000/statistics/admin/trade_statistics',
      );
      const statsData = await response.json();

      const workbook = new Excel.Workbook();
      const worksheet = workbook.addWorksheet('交易报表');

      worksheet.columns = [
        { header: '总交易数', key: 'total_trades' },
        { header: '交易银行卡总数', key: 'total_cards_traded' },
        { header: '总存款金额', key: 'total_deposit_amount' },
        { header: '总取款金额', key: 'total_withdraw_amount' },
        { header: '存款次数', key: 'deposit_count' },
        { header: '取款次数', key: 'withdraw_count' },
        { header: '平均交易金额', key: 'avg_trade_amount' },
        { header: '最大交易金额', key: 'max_trade_amount' },
        { header: '最小交易金额', key: 'min_trade_amount' },
      ];
      worksheet.getRow(1).font = { bold: true };

      for (const column of worksheet.columns) {
        if (column.header) {
          column.width = column.header.length + 10;
        }
        column.alignment = { horizontal: 'center' };
      }

      worksheet.addRow(statsData);

      worksheet.eachRow({ includeEmpty: false }, (row) => {
        row.eachCell((cell) => {
          cell.border = {
            top: { style: 'thin' },
            left: { style: 'thin' },
            bottom: { style: 'thin' },
            right: { style: 'thin' },
          };
        });
      });

      const buf = await workbook.xlsx.writeBuffer();
      saveAs(new Blob([buf]), 'trade_report.xlsx');
    } catch (error) {
      console.error('导出失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Button
      type="primary"
      onClick={handleExport}
      loading={loading}
      style={{ marginBottom: 16 }}
    >
      导出交易报表
    </Button>
  );
};

export default ExportTradeReport;
